import time
from datetime import datetime

import falcon

from WebBackend.middleware.virtualWorldGate_Chuche import login_require
from WebBackend.utils import mylog
from WebBackend.utils.encryption.myMD5 import create_md5
from WebBackend.utils.jwt_tools import generate_jwt, decode_jwt
import App_setting as setting


class Login:

    async def on_post(self, req, resp):
        t = await req.get_media()
        if t['password'] == create_md5(setting.security.server_admin_password):
            mylog.info(f'Login success', req.remote_addr)
            current_time = int(time.time())
            # 处理JWT过期时间
            jwt_expired_time = setting.security.jwt_expired_time
            jwt_expired_at = current_time + (1 if jwt_expired_time <= 0 else jwt_expired_time)
            jwt = generate_jwt(
                payload={'login_time': int(time.time())},
                expiry=jwt_expired_at
            )
            # 处理Cookie过期时间
            cookie_expired_time = setting.security.cookie_expired_time
            cookie_expired_at = current_time + cookie_expired_time if cookie_expired_time > 0 else 0
            resp.set_cookie(
                name='nibiru',
                value=jwt,
                max_age=cookie_expired_at,
                http_only=True,
                secure=setting.server.https,
            )
            resp.media = {
                "status": True,
                "text": "校验成功",
                "nibiru": jwt
            }
        else:
            resp.media = {
                "status": False,
                "text": "密码错误"

            }

    @falcon.before(login_require)
    async def on_delete(self, req: falcon.Request, resp: falcon.Response):
        jwt = req.context['jwt']
        resp.unset_cookie('nibiru')
        resp.text = 'ok'
